package com.hzhk.happyrent.ui.activity.personal;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.Constants;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.person.UploadBitmapModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.ui.activity.clip.ClipHeaderActivity;
import com.hzhk.happyrent.utils.BitmapUtils;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.SystemUtils;
import com.hzhk.happyrent.utils.glide.ShowImageUtils;
import com.tamic.novate.Throwable;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserInfoActivity extends AppCompatActivity {

    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.activity_titlebar_right)
    ImageView activityTitlebarRight;
    @BindView(R.id.user_header_image)
    ImageView userHeaderImage;
    @BindView(R.id.rl_user_header)
    RelativeLayout rlUserHeader;
    @BindView(R.id.user_nick_name)
    TextView userNickName;
    @BindView(R.id.rl_user_nick_name)
    RelativeLayout rlUserNickName;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.rl_user_phone)
    RelativeLayout rlUserPhone;
    @BindView(R.id.user_password)
    TextView userPassword;
    @BindView(R.id.rl_user_password)
    RelativeLayout rlUserPassword;

    private static final int CROP_PHOTO = 102;     //裁取圆形头像
    private static final int RESULT_LOAD_IMAGE = 0; //相册
    public static final int RESULT_CAMERA_IMAGE = 1; //拍照
    public static final int RESULT_NICK_CHANGE = 2;  //修改昵称

    private PopupWindow popupWindow;
    private View popView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        activityTitlebarCenter.setText(getResources().getString(R.string.user_info));
        if (!TextUtils.isEmpty(getIntent().getStringExtra(Constants.USER_HEADER))) {
            ShowImageUtils.showImageViewToCircleHolder(UserInfoActivity.this, getIntent().getStringExtra(Constants.USER_HEADER), userHeaderImage, R.drawable.person_header);
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra(Constants.USER_NICK_NAME))) {
            userNickName.setText(getIntent().getStringExtra(Constants.USER_NICK_NAME));
        } else {
            userNickName.setText(MyPerference.getInstance().getUserPhone());
        }
        userPhone.setText(MyPerference.getInstance().getUserPhone());
    }

    @OnClick({R.id.activity_titlebar_left, R.id.rl_user_header, R.id.rl_user_nick_name, R.id.rl_user_phone, R.id.rl_user_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_titlebar_left:
                finish();
                break;
            case R.id.rl_user_header:
                verifyStoragePermissions(UserInfoActivity.this);
                if(popupWindow==null){
                    showPopueWindow();
                }
                shootBottom();
                break;
            case R.id.rl_user_nick_name:
                Intent intent = new Intent(this, NickNameChangeActivity.class);
                intent.putExtra("nickname", userNickName.getText().toString());
                startActivityForResult(intent, RESULT_NICK_CHANGE);
                break;
            case R.id.rl_user_phone:
                break;
            case R.id.rl_user_password:
                startActivity(new Intent(this, PwdChangeActivity.class));
                break;
        }
    }

    private void showPopueWindow() {
        popView = View.inflate(this, R.layout.picture_get, null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels * 1 / 3;
        popupWindow = new PopupWindow(popView, weight, height);
        popupWindow.setAnimationStyle(R.style.dialog);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                popupWindow.dismiss();
            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takeCamera(RESULT_CAMERA_IMAGE);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
    }
    private void shootBottom(){
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
        TranslateAnimation animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, 1f,
                Animation.RELATIVE_TO_SELF, 0);
        animation.setDuration(200);
        popView.startAnimation(animation);
    }

    private void takeCamera(int num) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            photoFile = createImgFile();
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
            }
        }
        startActivityForResult(takePictureIntent, num);//跳转界面传回拍照所得数据
    }

    File tempFile;

    private File createImgFile() {
        //确定文件名
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = Environment.getExternalStorageDirectory();
        } else {
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        tempFile = new File(dir, fileName);
        try {
            if (tempFile.exists()) {
                tempFile.delete();
            }
            tempFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取文件路径
        return tempFile;
    }

    public static String generateFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        return imageFileName;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RESULT_LOAD_IMAGE:
                Uri selectedImage = data.getData();
                starCropPhoto(selectedImage);
                break;
            case RESULT_CAMERA_IMAGE:
                starCropPhoto(Uri.fromFile(tempFile));
                break;
            case CROP_PHOTO:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            case RESULT_NICK_CHANGE:
                if (data != null) {
                    if (!TextUtils.isEmpty(data.getStringExtra("nickname"))) {
                        userNickName.setText(data.getStringExtra("nickname"));
                    }
                }
                break;

            default:
                break;
        }
    }

    private static final String[] PERMISSION_EXTERNAL_STORAGE = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 100;

    private void verifyStoragePermissions(Activity activity) {
        int permissionWrite = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionWrite != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_EXTERNAL_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }


    /**
     * 打开截图界面
     *
     * @param uri 原图的Uri
     */
    public void starCropPhoto(Uri uri) {

        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipHeaderActivity.class);
        intent.setData(uri);
        intent.putExtra("side_length", 200);//裁剪图片宽高
        startActivityForResult(intent, CROP_PHOTO);
    }

    private void setPicToView(Intent picdata) {
        Uri uri = picdata.getData();
        if (uri == null) {
            return;
        }
        ShowImageUtils.showImageViewToCircleNoPlaceHolder(this, uri, userHeaderImage, 300);
//        userHeaderImage.setImageURI(uri);
        try {
            if (BitmapUtils.getBitmapFormUri(this, uri) != null) {
                postBitmap(BitmapUtils.getBitmapFormUri(this, uri));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    String userHeader;

    private void postBitmap(Bitmap bitmap) {
        Map<String, Object> params = new HashMap<>();
        params.put("data", SystemUtils.bitmapToBase64(bitmap));
        params.put("filename", generateFileName() + ".jpg");
        HttpManager.getInstance().perform_post(API.UPLOAD, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(PersonInfoActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                UploadBitmapModel uploadBitmapModel = new Gson().fromJson(response, UploadBitmapModel.class);
                userHeader = uploadBitmapModel.getData().getObject_url();
                postUserInfo();
            }
        });
    }

    private void postUserInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("id", MyPerference.getInstance().getUserId());
        if (!TextUtils.isEmpty(userHeader)) {
            params.put("avatar", userHeader);
        }
//        params.put("nickname", userHeader);
        HttpManager.getInstance().perform_post(API.EDIT_USER_INFO, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                Toast.makeText(UserInfoActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    Toast.makeText(UserInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
